var firstTab3 = true;

$(function() {
    $('#setTableTitle').blur(function(){
      freshPreview();
    });
  
    initDialog();
    initTab3();
    loadStyleTable();

	$('.tab2').click(function() {
       freshPreview();
	});
    
    //促销标签radio改变
    $("input[name=is_promotion_label]").click(function () {
      var beChecked = $('input[name=is_promotion_label]:checked').val();
      if(beChecked==='1'){
        $("input[name=promotion_label]").attr('disabled',false);
        $("input[name=promotion_position]").attr('disabled',false);
      }else{
        $("input[name=promotion_label]").attr('disabled',true);
        $("input[name=promotion_position]").attr('disabled',true);     
      }
    });
    
    //宝贝价格radio改变
    $("input[name=is_price]").click(function () {
      var beChecked = $('input[name=is_price]:checked').val();
      if(beChecked==='0'){
        $("input[name=price_style]").attr('disabled',true);
        $("input[name=price_label]").attr('disabled',true);
        $("#price_text").attr('disabled',true);
        $("#market_price").spinner('disable');
        $("#is_price_strike").attr('disabled',true);
      }else{
      	$("input[name=price_style]").attr('disabled',false);
		$("input[name=price_style]:checked").click();  
      }
    });
    
    //价格样式radio改变
    $("input[name=price_style]").click(function () {
      var beChecked = $('input[name=price_style]:checked').val();
      if(beChecked==='0'){
        $("input[name=price_label]").attr('disabled',true);
        $("#price_text").attr('disabled',true);
        $("#market_price").spinner('disable');
        $("#is_price_strike").attr('disabled',true);
      }else if(beChecked==='1'){
        $("#price_text").attr('disabled',true);
        $("#is_price_strike").attr('disabled',true);
        $("#market_price").spinner('disable');
        $("input[name=price_label]").attr('disabled',false);      
      }else if(beChecked==='2'){
        $("input[name=price_label]").attr('disabled',true);
        $("#price_text").attr('disabled',false);
        $("#is_price_strike").attr('disabled',false);  
        $("#market_price").spinner('enable');
      }
    });
    
    //购买按钮radio改变
    $("input[name=is_buy_button]").click(function () {
      var beChecked = $('input[name=is_buy_button]:checked').val();
      if(beChecked==='1'){
        $("input[name=buy_button]").attr('disabled',false);
      }else{
       $("input[name=buy_button]").attr('disabled',true);
      }
    });
     
    //客服radio改变
    $("input[name=is_wangwang]").click(function () {
      var beChecked = $('input[name=is_wangwang]:checked').val();
      if(beChecked==='1'){
        $("#wangwang").attr('disabled',false);
      }else{
        $("#wangwang").attr('disabled',true);
      }
    });
    
    //商城radio改变
    $("input[name=is_b_c]").click(function () {
      var beChecked = $('input[name=is_b_c]:checked').val();
      if(beChecked==='c'){
        $("#key_words").attr('disabled',false);
        $("input[name=is_wangwang]").attr('disabled',false);
        $("#wangwang").attr('disabled',false);
        $("#is_wangwang_div").attr('title',"");
        $("#key_words").attr('title',"");        
      }else{
        $("#key_words").attr('disabled',true);
        $("#key_words").val('');
        $("input[name=is_wangwang]").attr('disabled',true);
        $("#no_display_wangwang").attr("checked",'checked');
        $("#wangwang").attr('disabled',true);
        $("#is_wangwang_div").attr('title',"商城卖家暂不支持");
        $("#key_words").attr('title',"商城卖家暂不支持");         
      }
    }); 
    
});

function initTab3(){
  $("#market_price").spinner({ min: 101, max: 500 });
  var version_no = $("#version_no").val();
  if(Number(version_no)<= 1){ //体验版本
    $(".charge_style").attr('disabled',true);
    $("#key_words").attr('disabled',true);
    $("input[name=is_promotion_label]").attr('disabled',true);
    $("input[name=promotion_label]").attr('disabled',true);
    $("input[name=promotion_position]").attr('disabled',true);
    $("input[name=price_style]").attr('disabled',true);
    $("input[name=price_label]").attr('disabled',true);
    $("input[name=is_buy_button]").attr('disabled',true);
    $("input[name=buy_button]").attr('disabled',true);
    $("input[name=is_wangwang]").attr('disabled',true);
    $("input[name=is_fav]").attr('disabled',true);
    
    $("#price_text").attr('disabled',true);
    $("#is_price_strike").attr('disabled',true);
    $("#wangwang").attr('disabled',true);
    $("#market_price").spinner('disable');
    
    $("#text_price_style").attr("checked",'checked');
    $("#no_promotion_label").attr("checked",'checked');
    $("#no_buy_button").attr("checked",'checked');
    
    $("#key_words").attr('title',"付费用户专用，升级到更高版本");
    $(".charge_style_div").attr('title',"付费用户专用，升级到更高版本");
    $("#promotion_label_div").attr('title',"付费用户专用，升级到更高版本");
    $("#price_label_div").attr('title',"付费用户专用，升级到更高版本");
    $("#buy_button_div ").attr('title',"付费用户专用，升级到更高版本");
    $("#is_wangwang_div").attr('title',"付费用户专用，升级到更高版本");
    $("#is_fav_div").attr('title',"付费用户专用，升级到更高版本");
  }else{ //付费用户
    var is_b_c = $("input[name=is_b_c]:checked").val();
    if(is_b_c==='b'){
      $("#key_words").attr('disabled',true);
      $("#key_words").val('');
      $("input[name=is_wangwang]").attr('disabled',true);
      $("#is_wangwang_div").attr('title',"商城卖家暂不支持");
      $("#key_words").attr('title',"商城卖家暂不支持");
    }
    //默认图文式价格样式
    $("#pic_price_style").attr("checked",'checked');
    if(firstTab3){
    	$("#default_charge_promot_style").attr("checked",'checked');
    	firstTab3 = false;
    }
    $("#price_text").attr('disabled',true);
    $("#is_price_strike").attr('disabled',true);
    $("#market_price").spinner('disable');
    $("#wangwang").attr('disabled',true);
    $("#no_display_wangwang").attr("checked",'checked');
  }

}

function initDialog(){
   $('#step3_ipro_module').html("加载中，请稍等...");
   $('#dialog').dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 800
   });
     
   $('#dialog_style').dialog({
        autoOpen: false,
        resizable: false,
        modal: true,
        width: 800
   });
   
   $('#dialog_new_style').click(function(){
   	  var itemStr = getItems();
	  if(itemStr===''){
	    alert("请在第1步选择您要推广的宝贝！");
        return;
	  }
      $('#dialog_style').dialog('open');
      $('#styleName').val(getNowFormatDate());
      return false;
   });
}

/*
*新建样式时的预览
*/
function dialogPreview(){
    $('#dialog').dialog('open');
    preview();
    return false;
}

function dialogStyleSave(){
	var itemStr = getItems();
   	if(itemStr===''){
	  alert("请关闭样式设置页面，到第1步选择您要推广的宝贝！");
      return;
	}
    $.post("styleSave.action", getStyle(itemStr), processStyleSaveResponse, "json");
}

function processStyleSaveResponse(data,status){
	var code = data.result.code;
    var text = data.result.msg;
    if(code == "-1"){
    	alert(text);
    }
    else{
    	$('#dialog_style').dialog('close');
    	$("#styleTable").trigger("reloadGrid");
    }
}

function dialogStyleCancel(){
	$('#dialog_style').dialog('close');
}

/*
*新建样式时的预览
*/
function preview() {
	var itemStr = getItems();
	if(itemStr===''){
		$('#step3_ipro_module').html(
        "<div class='red fb f22'>请在第1步选择您要推广的宝贝</div>");
        return;
	}
    
    var params= getStyle(itemStr);
    params["userPro.TITLE"]= $('#setTableTitle').val();
    $.post("preview.action",params ,processPreviewResponse, "json");
}

function processPreviewResponse(data,status){
  $('#step3_ipro_module').html(data.result);
}

function getStyle(itemStr){
	var buy_button = $('input[name=buy_button]:checked').val();
    var price_label = $('input[name=price_label]:checked').val();
    var promotion_label= $('input[name=promotion_label]:checked').val()+"_"+$('input[name=promotion_position]:checked').val()+"_"+$('input[name=num_per_line]:checked').val();
    var layoutPosition = $('input[name=promotion_position]:checked').val();
    var num_per_line= $('input[name=num_per_line]:checked').val();
    var is_price_strike = $('input[name=is_price_strike]:checked').val();
    if(is_price_strike!='1'){
      is_price_strike ='0';
    }
    var params = {
     "userStyle.STANDARD_STYLE":$('input[name=promot_style]:checked').val(),
     "userStyle.BUY_BUTTON":buy_button,
     "userStyle.IS_BUY_BUTTON":$('input[name=is_buy_button]:checked').val(),
     "userStyle.IS_PRICE":$('input[name=is_price]:checked').val(),
     "userStyle.PRICE_LABEL":price_label,
     "userStyle.PRICE_STYLE":$('input[name=price_style]:checked').val(),
     "userStyle.IS_PRICE_STRIKE":is_price_strike,
     "userStyle.PROMOTION_LABEL":promotion_label,
     "userStyle.IS_PROMOTION_LABEL":$('input[name=is_promotion_label]:checked').val(),
     "userStyle.PROMOTION_POSITION":layoutPosition,
     "userStyle.IS_TITLE":$('input[name=is_title]:checked').val(),
     "userStyle.MARKET_PRICE":$('#market_price').val(), 
     "userStyle.PRICE_TEXT":$('#price_text').val(),
     "userStyle.NUM_PER_LINE":num_per_line,
     "userStyle.STATIC_FLAG":$('input[name=static_flag]:checked').val(),
     "userStyle.PRO4IPRO":$('input[name=pro4ipro]:checked').val(),
     "userStyle.INTELL_FIRST_FLAG":'1',
     "userStyle.KEY_WORDS":$('#key_words').val(),
     "userStyle.IS_FAV":$('input[name=is_fav]:checked').val(),
     "userStyle.IS_WANGWANG":$('input[name=is_wangwang]:checked').val(),
     "userStyle.WANGWANG":$('#wangwang').val(),
     "userStyle.STYLE_NAME":$('#styleName').val(),
     "userStyle.LAYOUT":getLayout(),
     //"userPro.TITLE":$('#setTableTitle').val(),
     "itemsStr":itemStr
    };
 	return params;
}

function getItems(){
    var oItems = getOrdinaryItems();
    var iItems = getIntelligenceItems();
    var items = iItems+oItems;
    if(items!==''){
      items = items.slice(0,items.length-1);
    }
    return items;
}

function getIntelligenceItems(){
    var beChecked = $('input[name=intell_switch]:checked').val();
    var intelligence_ipromotion_count = Number($('#num_1').val());
    if(beChecked=='intell_off'){
      intelligence_ipromotion_count = 0;
    }
    var oItems= "";
    for(var i=0;i<intelligence_ipromotion_count;i++){
        var item='{"iid":"-1","title":"安装时会被替换成具体的宝贝","picUrl":"http://img.ambitor.net/img/intell.jpg","price":"100.00"},';
        oItems+=item;
    }
    return oItems;
}

function getOrdinaryItems(){
    var iItems = "";
    $('.bePromoted').each(function() {
      var iid = $(this).attr('id');
      var price = $(this).attr('price');
      var title = $(this).attr('title');
          if(title.length>25){
            title= title.slice(0,25)+"...";
          }
      var img = $("#" + iid + ' img');
      var pic_url = img.attr('src');

      var item='{"iid":"'+iid+'","title":"'+title+'","picUrl":"'+pic_url+'","price":"'+price+'"},';
      iItems+=item;
    });
    return iItems;
}

function getLayout(){
  var result = "";
  var is_buy_button =$('input[name=is_buy_button]:checked').val();
  var is_title =$('input[name=is_title]:checked').val();
  var is_price =$('input[name=is_price]:checked').val();
  
  if(is_title=='1'){
    result+="item_title_code";
  }
  if(is_price=='1'){
    result+=",item_price_code";
  }
  if(is_buy_button=='1'){
    result+=",item_buy_button_code";
  }
  
  if(result.indexOf(',')===0){
    result=result.substring(1,result.length);
  }
  return result;
}


function loadStyleTable() {
  $("#styleTable").jqGrid({
    url: "queryStyle.action",
    datatype: "json",
    height: 200,
    width: 750,
    colNames: ["样式编码", "样式名称" , "宝贝图片大小", "安装位置", "是否显示促销标签", "是否显示购买按钮","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],
	colModel: [{name: "STYLE_ID",index: "STYLE_ID",align:"center",sortable: false},
			   {name: "STYLE_NAME",index: "STYLE_NAME",align:"center",sortable: false},
			   {name: "NUM_PER_LINE_DESC",index: "NUM_PER_LINE_DESC",align:"center",sortable: false},
			   {name: "INSTALL_PLACE_DESC",index: "INSTALL_PLACE_DESC",align:"center",sortable: false,hidden:true},
			   {name: "IS_PROMOTION_LABEL_DESC",index: "IS_PROMOTION_LABEL_DESC",align:"center",sortable: false,hidden:true},
			   {name: "IS_BUY_BUTTON_DESC",index: "IS_BUY_BUTTON_DESC",align:"center",sortable: false,hidden:true},
				{name: "USER_ID",index: "USER_ID",align:"center",hidden:true},
				{name: "STANDARD_STYLE",index: "STANDARD_STYLE",align:"center",hidden:true},
				{name: "BUY_BUTTON",index: "BUY_BUTTON",align:"center",hidden:true},
				{name: "PRICE_LABEL",index: "PRICE_LABEL",align:"center",hidden:true},
				{name: "PROMOTION_LABEL",index: "PROMOTION_LABEL",align:"center",hidden:true},
				{name: "MARKET_PRICE",index: "MARKET_PRICE",align:"center",hidden:true},
				{name: "NUM_PER_LINE",index: "NUM_PER_LINE",align:"center",hidden:true},
				{name: "STATIC_FLAG",index: "STATIC_FLAG",align:"center",hidden:true},
				{name: "BC_FLAG",index: "BC_FLAG",align:"center",hidden:true},
				{name: "INSTALL_PLACE",index: "INSTALL_PLACE",align:"center",hidden:true},
				{name: "PRO4IPRO",index: "PRO4IPRO",align:"center",hidden:true},
				{name: "INTELL_FIRST_FLAG",index: "INTELL_FIRST_FLAG",align:"center",hidden:true},
				{name: "PROMOTION_POSITION",index: "PROMOTION_POSITION",align:"center",hidden:true},
				{name: "PRICE_TEXT",index: "PRICE_TEXT",align:"center",hidden:true},
				{name: "KEY_WORDS",index: "KEY_WORDS",align:"center",hidden:true},
				{name: "TD_INTERVAL",index: "TD_INTERVAL",align:"center",hidden:true},
				{name: "IS_TITLE",index: "IS_TITLE",align:"center",hidden:true},
				{name: "IS_BUY_BUTTON",index: "IS_BUY_BUTTON",align:"center",hidden:true},
				{name: "IS_PRICE",index: "IS_PRICE",align:"center",hidden:true},
				{name: "PRICE_STYLE",index: "PRICE_STYLE",align:"center",hidden:true},
				{name: "IS_PRICE_STRIKE",index: "IS_PRICE_STRIKE",align:"center",hidden:true},
				{name: "IS_PROMOTION_LABEL",index: "IS_PROMOTION_LABEL",align:"center",hidden:true},
				{name: "IS_SALE_NUM",index: "IS_SALE_NUM",align:"center",hidden:true},
				{name: "SALE_TEXT",index: "SALE_TEXT",align:"center",hidden:true},
				{name: "IS_FAV",index: "IS_FAV",align:"center",hidden:true},
				{name: "DEFAULT_SALE_NUM",index: "DEFAULT_SALE_NUM",align:"center",hidden:true},
				{name: "LAYOUT",index: "LAYOUT",align:"center",hidden:true},
				{name: "IS_WANGWANG",index: "IS_WANGWANG",align:"center",hidden:true},
				{name: "WANGWANG",index: "WANGWANG",align:"center",hidden:true}],
    viewrecords: true,
    rowNum: 5,
    rowList: [5, 10],
    loadComplete: function () {
        setCellHeight('styleTable',30);
        setStyleTableSelection();
        freshPreview();
    },
    onSelectRow: function (rowid, status) {
       freshPreview();
    },
    jsonReader: {
      root: "dataset",
      page: "pager.curPageNo",
      total: "pager.totalPages",
      records: "pager.totalCount",
      repeatitems: false
    },
    prmNames: {
      rows: "pager.pageSize",
      page: "pager.curPageNo",
      sort: "pager.orderBy",
      order: "pager.order"
    },
    pager: "#stylePager",
    caption: "选择已有样式"
  });
}

function setStyleTableSelection() {
  var records = $("#styleTable").jqGrid("getGridParam", "records");
  if(records==null){
    return;
  }
  if(records > 0){
    $("#styleTable").setSelection(1);
  }else{
  }
}

/**
*获取表格中的样式
*/
function getChooseStyle(itemStr,ret){
    var params = {
     "userStyle.STANDARD_STYLE":ret.STANDARD_STYLE,
     "userStyle.TITLE":ret.TITLE,
     "userStyle.BUY_BUTTON":ret.BUY_BUTTON,
     "userStyle.IS_BUY_BUTTON":ret.IS_BUY_BUTTON,
     "userStyle.IS_PRICE":ret.IS_PRICE,
     "userStyle.PRICE_LABEL":ret.PRICE_LABEL,
     "userStyle.PRICE_STYLE":ret.PRICE_STYLE,
     "userStyle.IS_PRICE_STRIKE":ret.IS_PRICE_STRIKE,
     "userStyle.PROMOTION_LABEL":ret.PROMOTION_LABEL,
     "userStyle.IS_PROMOTION_LABEL":ret.IS_PROMOTION_LABEL,
     "userStyle.PROMOTION_POSITION":ret.PROMOTION_POSITION,
     "userStyle.IS_TITLE":ret.IS_TITLE,
     "userStyle.MARKET_PRICE":ret.MARKET_PRICE, 
     "userStyle.PRICE_TEXT":ret.PRICE_TEXT,
     "userStyle.NUM_PER_LINE":ret.NUM_PER_LINE,
     "userStyle.STATIC_FLAG":ret.STATIC_FLAG,
     //"userStyle.INSTALL_PLACE":ret.INSTALL_PLACE,
     "userStyle.PRO4IPRO":ret.PRO4IPRO,
     "userStyle.INTELL_FIRST_FLAG":ret.INTELL_FIRST_FLAG,
     "userStyle.KEY_WORDS":ret.KEY_WORDS,
     "userStyle.IS_FAV":ret.IS_FAV,
     "userStyle.IS_WANGWANG":ret.IS_WANGWANG,
     "userStyle.WANGWANG":ret.WANGWANG,
     "userStyle.STYLE_NAME":ret.STYLE_NAME,
     "userStyle.LAYOUT":ret.LAYOUT,
     "userPro.TITLE":$('#setTableTitle').val(),
     "itemsStr":itemStr
    };
 	return params;
}

//刷新重新加载预览
function freshPreview(){
	var  rowid = $("#styleTable").getGridParam( "selrow" ); 
	if (rowid === null) {
        return;
    }
    var itemStr = getItems();
	if(itemStr===''){
		$('#choose_style_preview').html(
	     "<div class='red fb f22'>请在第1步选择您要推广的宝贝</div>")
	    return;
	}
    var ret = $("#styleTable").jqGrid("getRowData", rowid);
    $('#choose_style_preview').html("<br />正在加载预览，请稍等...<br />");
    $.post("preview.action", getChooseStyle(itemStr,ret),processChooseStylePreviewResponse, "json");
}

function processChooseStylePreviewResponse(data,status){
  $('#choose_style_preview').html(data.result);
}